package com.apache.passport.service;

import com.apache.api.api.ApiService;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.exception.ServiceException;
import com.apache.license.validator.LicenseValidate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * description:  单点登录服务
 *
 * @author Hou Dayu 创建时间：2016-12-18
 */
public class SsoServiceImpl implements ApiService {

    private static final Logger log = LoggerFactory.getLogger(SsoServiceImpl.class);

    private Map<String, PluginConnector> plugins;

    public ResultEntity doService(ParamsVo vo) throws ServiceException {
        ResultEntity result = new ResultEntity();
        result.setResult("true");
        String key = vo.getMethodKey();
        Object obj = plugins.get(key);
        if (Validator.isEmpty(obj)) {
            result.setEntity("F");
            result.setMessage("您访问的服务不存在或未启用");
            log.info("passport msg:[{}]", "您访问的服务不存在或未启用");
        } else {
            try {
                if (LicenseValidate.getInstance().isEffective()) {//验证系统license
                    ResultEntity ent = null;
                    boolean flag = false;
                    //在操作前,首先执行下,当前访问的系统是否有权限支持
                    if (plugins.get("checkSys").execute(vo) instanceof Boolean) {
                        flag = (Boolean) plugins.get("checkSys").execute(vo);
                    } else if (plugins.get("checkSys").execute(vo) instanceof ResultEntity) {
                        ent = (ResultEntity) plugins.get("checkSys").execute(vo);
                        String str = (String) ent.getEntity();
                        if (!"F".equals(str)) {
                            flag = true;
                        }
                    }
                    if (flag) {
                        return (ResultEntity) plugins.get(vo.getMethodKey()).execute(vo);
                    } else if (!Validator.isEmpty(ent)) {
                        return ent;
                    } else {
                        result.setEntity("O");
                        log.info("passport msg:[{}]", "当前系统没有服务使用权限");
                    }
                } else {
                    result.setMessage("功能已停用或已删除！");
                    log.error("系统license已过期,请重新申请license文件");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public void setPlugins(Map<String, PluginConnector> plugins) {
        this.plugins = plugins;
    }
}
